package jsu.blogger.controller;

import jakarta.servlet.http.HttpServletRequest;
import jsu.blogger.pojo.Comment;
import jsu.blogger.pojo.Result;
import jsu.blogger.service.impl.SystemNoticeService;
import jsu.blogger.service.inter.CommentService;
import jsu.blogger.service.inter.GetUserDataService;
import jsu.blogger.service.inter.LiveService;
import jsu.blogger.util.ReturnResultUtil;
import org.apache.ibatis.annotations.Delete;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CommentController {
    private static final Logger log = LoggerFactory.getLogger(CommentController.class);
    @Autowired
    private CommentService commentService;
    @Autowired
    LiveService liveService;
    @Autowired
    private GetUserDataService getUserDataService;
    @GetMapping("/getComments/parent/{postId}/{begin}/{count}")
//  根据帖子获取这个帖子的一级评论情况
    public Result getParentComment(@PathVariable Long postId,@PathVariable int begin,@PathVariable int count) {
        Map<String, Object> reMap = new HashMap<>();
        List<Comment> results=commentService.getParentComments(postId,begin,count);
        List<HashMap<String,Object>> comments=new ArrayList<>();
        results.forEach(comment->{
            HashMap<String,Object> map=new HashMap<>();
            map.put("comment",comment);
            map.put("username",getUsername(comment.getUserId()));
            comments.add(map);
        });
        reMap.put("comments",comments);
        return ReturnResultUtil.success(reMap);
    }
    @GetMapping("/getComments/son/{postId}/{parentCommentId}/{begin}/{count}")
    //  根据帖子获取这个帖子的二级评论情况
    public Result getSonComment(@PathVariable Long postId,@PathVariable Long parentCommentId,@PathVariable int begin,@PathVariable int count) {
        Map<String, Object> reMap = new HashMap<>();
        List<Comment> results=commentService.getSonComments(postId,parentCommentId,begin,count);
        List<HashMap<String,Object>> comments=new ArrayList<>();
        results.forEach(comment->{
            HashMap<String,Object> map=new HashMap<>();
            map.put("comment",comment);
            map.put("username",getUsername(comment.getUserId()));
            comments.add(map);
        });
        reMap.put("comments",comments);
        return ReturnResultUtil.success(reMap);
    }
    @PostMapping("/setComment")
    public Result setComment(HttpServletRequest request) {
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        Long postId = Long.valueOf((Integer)map.get("postId"));
        Long userId =Long.valueOf((Integer)map.get("userId"));
        Long parentCommentId=null;
        Long replyToUserId=null;
        if( map.get("parentCommentId")!=null)
         parentCommentId= Long.valueOf((Integer)map.get("parentCommentId"));
        if(map.get("replyToUserId")!=null)
        replyToUserId=Long.valueOf((Integer)map.get("replyToUserId"));
        String content = (String) map.get("content");
        Timestamp createdAt=null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 根据您的日期格式进行调整
        try {
            java.util.Date parsedDate = format.parse(map.get("createdAt").toString());
            createdAt = new Timestamp(parsedDate.getTime());
        } catch (ParseException e) {
            e.printStackTrace(); // 处理解析异常
        }
        if(commentService.insertComment(postId,userId,parentCommentId,replyToUserId,content,createdAt)==1){
            if(parentCommentId==null){//进行评论通知
                log.info("帖子评论通知");
                SystemNoticeService.noticePostComment(userId,liveService.getUserIdByPostId(postId),postId,content,getUserDataService.getUsernameByUserId(userId),liveService.getLiveContent(postId),createdAt);
            }else{
                log.info("评论回复通知");
                SystemNoticeService.noticeReply(userId,replyToUserId,postId,getUserDataService.getUsernameByUserId(userId),commentService.getParentComment(parentCommentId),content,createdAt);
            }
            return ReturnResultUtil.success();
        }else {
            log.info("用户" + userId + "插入帖子" + postId + "失败");
            return ReturnResultUtil.failure("评论插入失败");
        }
    }
    @GetMapping("/deleteComment/{commentId}/{userId}")
    public Result deleteComment(@PathVariable Long commentId,@PathVariable Long userId) {
        if(commentService.deleteComment(commentId,userId)){
            return ReturnResultUtil.success();
        }else{
            log.info("用户" + userId + "删除评论" + commentId + "失败");
            return ReturnResultUtil.failure("评论删除失败");
        }
    }
    public String getUsername(Long userId){
        String username=null;
        if(userId!=null){
            username= getUserDataService.getUsernameByUserId(userId);
        }
        return username;
    }
}